<template>
  <el-row>
    <div class="__head">
      <el-menu class="_menu"
               :default-active="defaultActiveMenu"
               background-color="#545c64"
               text-color="#fff"
               active-text-color="#ffd04b"
               mode="horizontal"
               @select="menuSelect">
        <el-menu-item :index="`/${project.name}`">
          <span class="menu-icon"><i class="el-icon-menu"></i></span>
        </el-menu-item>
        <s-menu :menu="USER.menu"></s-menu>
      </el-menu>
      <div class="__menu title" @click="titleClick">
        <div role="menuitem" tabindex="-1" class="el-menu-item __li is-active main" style="padding-left:20px;color:#ffd04b;background-color:#545c64;" data-v-66cdaffe="">
        <span class="menu-icon" data-v-66cdaffe="">
          <i class="menuIcon fa fa-bars" data-v-66cdaffe=""></i>
        </span>
          <span class="__title" data-v-66cdaffe="">统一报销平台</span>
        </div>
      </div>
      <div class="__menu title">
        <div role="menuitem" tabindex="-1" class="el-menu-item __li is-active" style="padding-left:20px;color:#ffd04b;background-color:#545c64;" data-v-66cdaffe="">
        <span class="menu-icon" data-v-66cdaffe="">
          <i class="menuIcon fa fa-bars" data-v-66cdaffe=""></i>
        </span>
          <span class="__title" data-v-66cdaffe="">统一报销平台</span>
        </div>
      </div>
      <el-collapse-transition>
        <div v-if="title">
          <el-menu class="__menu body"
                   :default-active="defaultActiveMenu"
                   background-color="#545c64"
                   text-color="#fff"
                   active-text-color="#ffd04b"
                   @select="menuSelect">
            <el-menu-item
              class="__li"
              :index="`/${project.name}`">
              <span slot="title">首页</span>
            </el-menu-item>
            <s-menu :menu="USER.menu"></s-menu>
          </el-menu>
        </div>
      </el-collapse-transition>
    </div>
    <div class="__user">
      <el-popover
        popper-class="__user-popper"
        placement="right"
        trigger="click">
        <p><span class="label">用户姓名</span>
          <el-tag type="primary" size="small">{{USER.user.name}}</el-tag>
        </p>
        <p><span class="label">所属客户</span>
          <el-tag type="warning" size="small">{{USER.user.show_rent || '未知'}}</el-tag>
        </p>
        <p><span class="label">所属机构</span>
          <el-tag type="primary" size="small">{{USER.user.orgName || '暂无机构'}}</el-tag>
        </p>
        <slot name="content">
          <div>
            <el-row>
              <el-button class="user-button" @click="open">新的面板</el-button>
            </el-row>
            <el-row>
              <el-button class="user-button" type="success" @click="dialogOpen()">详细信息</el-button>
            </el-row>
            <el-row>
              <el-button class="user-button" type="warning" v-if="!AutoVue_loading" @click="AutoVue_lock(true)">锁定页面</el-button>
            </el-row>
            <el-row>
              <el-button class="user-button" type="danger" @click="logout">退出系统</el-button>
            </el-row>
          </div>
        </slot>
        <img slot="reference" class="photo" :src="photo"/>
      </el-popover>
    </div>
    <div class="__user_lock" v-if="AutoVue_loading">
      <h1>用户暂时离开中</h1>
      <s-form
        :form="form_AutoVuePassword"
        ref="form_AutoVuePassword">
        <el-form-item prop="AutoVue_password">
          <el-input type="password" v-model="form_AutoVuePassword.AutoVue_password" placeholder="密码"
                    auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
        </el-form-item>
        <button id="login-button" @click.prevent="AutoVue_lock(false)" tabindex="3">解锁</button>
      </s-form>
    </div>
    <nuxt-child/>
    <s-dialog :dialog="dialog" :close="dialogInit" :closeTip="dialog.modify">
      <p slot="title">{{dialog.modify?'修改 ':''}}用户信息</p>
      <s-form :form="formDialog" ref="formDialog">
        <div v-if="!dialog.modify">
          <el-row>
            <el-col :xs="24" :lg="{span: 11, offset: 0}">
              <el-form-item prop="show_rent" label="所属客户"><span>{{formDialog.show_rent}}</span></el-form-item>
            </el-col>
            <el-col :xs="24" :lg="{span: 11, offset: 1}">
              <el-form-item prop="userAccount" label="用户账号"><span>{{formDialog.userAccount}}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :lg="{span: 11, offset: 0}">
              <el-form-item prop="name" label="用户姓名"><span>{{formDialog.name}}</span></el-form-item>
            </el-col>
            <el-col :xs="24" :lg="{span: 11, offset: 1}">
              <el-form-item prop="orgName" label="机构名称"><span>{{formDialog.orgName}}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :lg="{span: 11, offset: 0}">
              <el-form-item prop="email" label="电子邮箱"><span>{{formDialog.email}}</span></el-form-item>
            </el-col>
            <el-col :xs="24" :lg="{span: 11, offset: 1}">
              <el-form-item prop="mobile" label="手机号"><span>{{formDialog.mobile}}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :lg="{span: 11, offset: 0}">
              <el-form-item prop="locked" label="锁定状态"><span>{{parseInt(formDialog.locked) > 0 ? '已锁定':'未锁定'}}</span></el-form-item>
            </el-col>
            <el-col :xs="24" :lg="{span: 11, offset: 1}">
              <el-form-item prop="createMan" label="创建人"><span>{{formDialog.createMan}}</span></el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="createDate" label="创建时间">
            <span>
                {{formatterTime(formDialog.createDate, 1)}}
            </span>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item prop="photo" label="用户头像" class="form_item_user">
            <el-upload
              class="upload-user"
              :action="action"
              name="userPhoto"
              :show-file-list="false"
              :on-success="uploadUserSuccess"
              :before-upload="uploadUserUpload">
              <img v-if="formDialog.photo" :src="photo" class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item prop="email"
                        :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }]"
                        label="电子邮箱">
            <el-input type="text"
                      v-model="formDialog.email"
                      placeholder="电子邮箱" spellcheck="false" auto-capitalize="off" auto-complete="off"
                      auto-correct="off"></el-input>
          </el-form-item>
          <el-form-item prop="mobile"
                        label="手机号">
            <el-input type="text"
                      v-model="formDialog.mobile"
                      placeholder="手机号" spellcheck="false" auto-capitalize="off" auto-complete="off"
                      auto-correct="off"></el-input>
          </el-form-item>
        </div>
      </s-form>
      <el-button slot="footer" :type="dialog.modify?'warning':'success'" @click="dialog.modify = !dialog.modify">{{dialog.modify?'查看':'修改'}}信息</el-button>
      <el-button slot="footer" v-if="!dialog.modify" @click="dialogPwdOpen">修改密码</el-button>
      <el-button slot="footer" type="info" v-if="!dialog.modify" @click="dialogSave(true)">好</el-button>
      <el-button slot="footer" type="info" v-else @click="dialogSave(false)">保存</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogPwd" :close="dialogInit">
      <p slot="title">修改密码</p>
      <s-form :form="formDialogPwd" ref="formDialogPwd">
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="oldPwd" label="原密码">
              <el-input
                type="password"
                v-model="formDialogPwd.oldPwd"
                placeholder="原密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="newPwd"
                          :rules="[{ validator: validatePass, trigger: 'blur' }]"
                          label="新密码">
              <el-input
                type="password"
                v-model="formDialogPwd.newPwd"
                placeholder="新密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}">
            <el-form-item prop="newPwd2"
                          :rules="[{ validator: validatePass2, trigger: 'blur' }]"
                          label="重复新密">
              <el-input
                type="password"
                v-model="formDialogPwd.newPwd2"
                placeholder="重复新密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" type="info" @click="changePwd">保存</el-button>
    </s-dialog>
  </el-row>
</template>

<script>
  import {
    AutoVue,
    Drag,
    SetLoading,
    UnsetLoading,
    GetLoading,
    Log,
  } from '~/plugins/Tools';
  import menu from '~/components/public/menu.vue';
  import Config from '~/config';

  let {
    Local,
    SSO,
    PublicImageServer,
  } = Config;

  let loadingInstance = 0;

  function __dialogPwd () {
    return {
      formRef: 'formDialogPwd',
    };
  }
  function __dialog () {
    return {
      title: '',
      modify: false,
      formRef: 'formDialog',
    };
  }
  function __form () {
    return { address: { value: '', rule: [] },
      birthday: { value: '', rule: [] },
      childrenName: { value: '', rule: [] },
      colleage: { value: '', rule: [] },
      createDate: { value: '', rule: [] },
      createMan: { value: '', rule: [] },
      email: { value: '', rule: [] },
      empLevel: { value: 0, rule: [] },
      gender: { value: '', rule: [] },
      graduteDate: { value: '', rule: [] },
      graduteLevel: { value: 0, rule: [] },
      id: { value: 0, rule: [] },
      joinDate: { value: '', rule: [] },
      lastlogintime: { value: '', rule: [] },
      lockTime: { value: '', rule: [] },
      locked: { value: 0, rule: [] },
      major: { value: '', rule: [] },
      married: { value: 0, rule: [] },
      mateMobile: { value: '', rule: [] },
      mateName: { value: '', rule: [] },
      mobile: { value: '', rule: [] },
      name: { value: '', rule: [] },
      nativePlace: { value: '', rule: [] },
      orgId: { value: undefined, rule: [] },
      orgName: { value: '', rule: [] },
      photo: { value: '', rule: [] },
      piliticalFace: { value: '', rule: [] },
      position: { value: '', rule: [] },
      race: { value: '', rule: [] },
      rentId: { value: 0, rule: [] },
      show_rent: { value: '', rule: [] },
      show_type: { value: '', rule: [] },
      telephone: { value: '', rule: [] },
      type: { value: 0, rule: [] },
      updateDate: { value: '', rule: [] },
      updateMan: { value: '', rule: [] },
      userAccount: { value: '', rule: [] },
      userPassword: { value: '', rule: [] },
      workHis: { value: '', rule: [] },
      workState: { value: 0, rule: [] } };
  }
  function __formPwd () {
    return { oldPwd: { value: '', rule: ['vNull', 'v_UserPassword'], cRemarks: '' },
      newPwd: { value: '', rule: ['vNull'], cRemarks: '' },
      newPwd2: { value: '', rule: [], cRemarks: '' } };
  }
  function __formDialogHz () {
    return {
      hzid: { value: '', rule: ['vNull__change'], cRemarks: '' },
    };
  }

  export default AutoVue({
    name: `index-${Local.name}`,
    store: ['USER'],
    computed: {
      photo: function () {
        if (this.USER.user.photo) {
          return PublicImageServer.src + '/image/userPhoto/' + this.USER.user.photo;
        } else {
          return PublicImageServer.src + (this.USER.user.gender === '女' ? '/image/userPhoto/base2.png' : '/image/userPhoto/base1.png');
        }
      },
      action: function () {
        let params = '';
        if (this.formDialog.photo && this.formDialog.photo !== 'base1.png' && this.formDialog.photo !== 'base2.png') {
          params = '?imageOldName=' + this.formDialog.photo;
        }
        return PublicImageServer.src + `/${PublicImageServer.upload}/${PublicImageServer.userPhoto}` + params;
      },
      defaultActiveMenu: function () {
        return this.$route.path;
      },
    },
    data: {
      title: false,
      AutoVue_loading: false,
      AutoVue_password: '',
      dialogPwd: __dialogPwd(),
      dialogWebSocket: {},
      dialog: __dialog(),
      formDialog: __form(),
      formDialogPwd: __formPwd(),
      form_AutoVuePassword: {
        'AutoVue_password': {
          value: '',
          rule: ['vNull'],
        },
      },
      project: Local,

      dialogHz: {
        size: 'mini',
        hz: [],
        user: {},
        HZ: {},
      },
      formDialogHz: __formDialogHz(),
    },
    components: {
      's-menu': menu,
    },
    methods: {
      titleClick () {
        this.title = !this.title;
      },
      validatePass: function (rule, value, callback) {
        if ((value + '').length < 6 && (value + '').length !== 0) {
          if (this.formDialogPwd.newPwd2 !== '') {
            this.$refs.formDialogPwd.$refs.formDialogPwd.validateField('newPwd2');
          }
          callback(new Error('请输入不少于6位的密码'));
        } else {
          if (this.formDialogPwd.newPwd2 !== '') {
            this.$refs.formDialogPwd.$refs.formDialogPwd.validateField('newPwd2');
          }
          callback();
        }
      },
      validatePass2: function (rule, value, callback) {
        if (this.formDialogPwd.newPwd === '') {
          this.formDialogPwd.newPwd2 = '';
          callback();
        }
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.formDialogPwd.newPwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      menuSelect (key, keyPath) {
        if (key.indexOf('-') !== -1) return;
        this.$router.push(key);
      },
      async logout () {
        try {
          await this.p({
            method: SSO.logoutMethod,
            url: SSO.ssoLogout,
          });
        } catch (err) {
          console.log(err);
        } finally {
          this.DEL('USER');
          try {
            await this.get('/' + Local.userOut);
          } finally {
            window.location.replace(`${Local.url}/login`);
          }
        }
      },
      changePwd () {
        this.VALIDATE('formDialogPwd', async option => {
          try {
            await this.post('/sysuser/editPwd', {
              'oldPwd': option.oldPwd,
              'newPwd': option.newPwd,
              'id': this.USER.user.id,
            });
            this.dialogPwd.visible = false;
          } catch (err) {
            console.log(err);
          }
        });
      },

      dialogInit (formRef = 'formDialog') {
        this.dialog.modify = false;
        this.resetFields(formRef);
      },
      dialogOpen () {
        this.formDialog = Object.assign(this.formDialog, this.USER.user);
        this.dialog.visible = true;
      },
      async dialogSave (ok) {
        if (ok) {
          this.dialog.visible = false;
          return;
        }
        try {
          let option = this.formDialog;
          let prop = {
            id: this.USER.user.id,
            mobile: option.mobile,
            email: option.email,
          };
          await this.post('/sysuser/update', prop);
          this.SET('USER_user', {
            ...this.USER.user,
            mobile: option.mobile,
            email: option.email,
          });
          this.dialogInit();
          this.dialog.visible = false;
        } catch (err) {
          console.log(err);
        }
      },

      dialogHzInit () {
        this.dialogHz.modify = false;
        this.dialogHz.user = {};
        this.formDialogHz = {
          ...this.formDialogHz,
          ...this.ObjectClone(__formDialogHz()),
        };
        this.resetFields('formDialogHz');
      },
      async dialogHzOpen () {
        this.dialogHz.user = Object.assign(this.formDialog, this.USER.user);
        if (this.dialogHz.hz.length === 0) {
          let {id} = await this.post('/sysuser/switchSelectId');
          this.dialogHz.hz = id;
        }
        this.dialogHz.visible = true;
      },
      selectChangeHzid (id) {
        this.dialogHz.hz.forEach(item => {
          if (id === item.id) {
            this.dialogHz.HZ = item;
          }
        });
      },
      dialogHzSave () {
        this.VALIDATE('formDialogHz', async option => {
          try {
            let json = {
              ...option,
              show_hzid: this.dialogHz.HZ.mc,
            };
            await this.post('/sysuser/switchShipper', json);
            this.SET('USER_hz', json);
            this.dialogHzInit();
            this.dialogHz.visible = false;
          } catch (err) {
            console.log(err);
          }
        });
      },

      uploadUserSuccess (res, file) {
        this.formDialog.photoURL = URL.createObjectURL(file.raw);
        this.formDialog.photo = res.filename;
        if (res.error) {
          return this.$alert(res.error);
        }
        this.post('/sysuser/updateImg', {
          userId: this.USER.user.id,
          path: res.filename,
        });
        this.SET('USER_photo', res.filename);
      },
      uploadUserUpload (file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG 与 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
      },

      AutoVue_lock (lock) {
        if (lock) {
          this.$prompt('请输入临时密码', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({value}) => {
            this.AutoVue_password = value;
            this.AutoVue_loading = true;
            loadingInstance = this.$loading({fullscreen: true});
            SetLoading(value);
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消锁定',
            });
          });
        } else {
          this.VALIDATE('form_AutoVuePassword', option => {
            let {AutoVue_password} = option;
            if (AutoVue_password === this.AutoVue_password) {
              this.AutoVue_password = '';
              this.form_AutoVuePassword.AutoVue_password = '';
              this.AutoVue_loading = false;
              loadingInstance.close();
              UnsetLoading();
            } else {
              this.$message({
                type: 'info',
                message: '密码错误',
              });
            }
          });
        }
      },
      dialogPwdOpen () {
        this.dialogPwd.visible = true;
      },
      open () {
        window.open(this.$route.path);
      },
    },
    mounted () {
      if (!process.browser) return;
      let cons = new Log();
      cons.lH = 'Vue 初始化成功！';
      let elUser = this.$el.querySelector('.__user');
      cons.l = '开启 头像Drag 服务';
      Drag(elUser, elUser);
      cons.l = '开启 锁定页面 服务';
      loadingInstance = setInterval(() => {
        let {
          AutoVue_loading,
          AutoVue_password,
        } = GetLoading();
        if (AutoVue_loading && !this.AutoVue_loading) {
          this.AutoVue_loading = true;
          loadingInstance = this.$loading({fullscreen: true});
          this.AutoVue_password = AutoVue_password;
        } else if (!AutoVue_loading && this.AutoVue_loading) {
          this.AutoVue_loading = false;
          this.AutoVue_password = '';
          this.form_AutoVuePassword.AutoVue_password = '';
          loadingInstance.close();
        }
      }, 1000);
      cons.log();
      console.log(this);
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  @import "../assets/css/keyframes/breathe";

  $user: 80px;
  $user-xs: 60px;
  .__user {
    cursor: move;
    position: fixed;
    right: 200px;
    top: 10px;
    z-index: 9999;
    border-radius: 50%;
    overflow: hidden;
    width: $user;
    height: $user;
    .photo {
      width: $user;
      height: $user;
    }
    transition: box-shadow 1s;
    box-shadow: 0 1px 2px rgba(255, 255, 255, 0.1);
    &:hover {
      box-shadow: 0 1px 30px rgba(32, 160, 255, 1);
      animation: breathe-Opacity 1s forwards;
    }
  }

  .__user_lock {
    position: fixed;
    z-index: 10001;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 400px;
    height: 400px;
    h1 {
      text-align: center;
    }
  }

  @media screen and (max-width: 800px) {
    .__user {
      right: 20px;
      top: 10px;
      width: $user-xs;
      height: $user-xs;
      .photo {
        width: $user-xs;
        height: $user-xs;
      }
    }
  }
</style>

<style lang="scss">

  .__user-popper {
    max-width: 200px;
    p {
      margin: 0;
      padding: 0;
      .label {
        display: inline-block;
        width: 60px;
      }
    }
    .user-button {
      width: 100%;
      margin-top: 5px;
    }
  }

  .__head {
    ._menu, .__menu {
      width: 100vw;
    }
    ._menu {
      display: block;
    }
    .body {
      position: fixed;
      z-index: 100;
    }
    .__menu {
      .control {
        display: block;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 107px;
      }
      .main{
        position: fixed!important;
        top: 0;
        width: 100%;
        z-index: 100;
      }
      display: none;
    }
  }

  .__menu_drop {
    padding: 0;
    margin: 0;
    .el-menu-item {
      min-width: 200px;
    }
  }

  @media screen and (max-width: 800px) {
    .__head {
      ._menu {
        display: none;
      }
      .__menu {
        display: block;
        /**
         * 统一报平台居中显示
         */
        .__li {
          position: relative;
          .__title {
            position: absolute;
            display: block;
            top: 0;
            left: 0;
            right: 0;
            margin: auto;
            width: 85px;
          }
        }
      }
    }
  }

  .menu-icon{
    width: 22px;
    display: inline-block;
    text-align: center;
  }
</style>
